﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Newtonsoft.Json;

namespace PlayerManager
{
    public struct PlayerData
    {
        public String Name;
        public UInt64 Money;
        public int Rank;
    }


    public partial class Form1 : Form
    {
        //all loaded player data
        List<PlayerData> L_PD_PlayerData = new List<PlayerData>();
        List<String> L_S_PlayerDataLoc = new List<String>();
        PlayerData SelectedPlayerData = new PlayerData();
        int NewFileCnt = 0;
        bool Ask = true;
        
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ClrReset();
            Load_DataBase(true);
        }
        private void RefNotActuallyUsed()
        {
            //MessageBox.Show(string.Format("You selected: {0}", e.Node.Text));
            //PlayerData ClickedPlayer = L_PD_PlayerData[int.Parse(e.Node.Text[1].ToString())];
            //l_Name.Text = "Name: " + ClickedPlayer.Name;
            //l_Money.Text = string.Format("Money: {0,0:N0}", ClickedPlayer.Money);
            //l_Rank.Text = "Rank: " + ClickedPlayer.Rank;

            //make & write
            PlayerData June;
            June.Name = "June";
            June.Money = 9001;
            June.Rank = 255;

            String Temp = JsonConvert.SerializeObject(June);
            File.WriteAllText("June.txt", Temp);

            //read & make
            String Temp2 = File.ReadAllText("June.txt");
            PlayerData June2;
            June2 = JsonConvert.DeserializeObject<PlayerData>(Temp2);

            TreeNode Dev = new TreeNode(June2.Name);
            treeView1.Nodes.Add(Dev);
        }
        
        //get all text files from disk and json parse them into classes
        private void Load_DataBase(bool ShowMSG)
        {
            String[] PlayerFiles = Directory.GetFiles(Directory.GetCurrentDirectory());
            //MessageBox.Show(JsonConvert.SerializeObject(PlayerFiles));
            int ValidPlayers = 0;
            int InValidPlayers = 0;
            for (int Index = 0; Index < PlayerFiles.Length; Index++)
            {
                if (PlayerFiles[Index].Substring(PlayerFiles[Index].Length - 4).ToLower() == ".txt")
                {
                    try
                    {
                        string JsonText = File.ReadAllText(PlayerFiles[Index]);
                        PlayerData TempPlayer;
                        TempPlayer = JsonConvert.DeserializeObject<PlayerData>(JsonText);
                        L_PD_PlayerData.Add(TempPlayer);
                        L_S_PlayerDataLoc.Add(PlayerFiles[Index]);
                        ValidPlayers++;
                    }
                    catch
                    {
                        InValidPlayers++;
                    }
                }
                else
                {
                    InValidPlayers++;
                }
            }
            Build_TreeNodes();
            if (ShowMSG)
            {
                MessageBox.Show(ValidPlayers + " Valid Players Loaded, " + InValidPlayers + " File(s) was not valid and ingnored.");
            }
        }
        private void Build_TreeNodes()
        {
            treeView1.Nodes.Clear();
            
            //Each Playerdata in the player data list
            for (int Index = 0; Index < L_PD_PlayerData.Count; Index++)
            {
                //get the current index Playerdata's Name string
                //treeView1.Nodes.Add("[" + Index +"] "+ L_PD_PlayerData[Index].Name);
                treeView1.Nodes.Add(L_PD_PlayerData[Index].Name);
            }
        }



        // If a node is double-clicked, open the file indicated by the TreeNode. 
        void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            
            SelectedPlayerData = L_PD_PlayerData[e.Node.Index];
            
            textBox1.Text = "" + SelectedPlayerData.Name;
            textBox2.Text = "" + SelectedPlayerData.Money;
            textBox3.Text = "" + SelectedPlayerData.Rank;
            Save.Enabled = true;
            Delete.Enabled = true;
            textBox1.Enabled = true;
            textBox2.Enabled = true;
            textBox3.Enabled = true;
        }
        //clears and resets the displayed info
        void ClrReset()
        {
            l_Name.Text = "Name:";
            l_Money.Text = "Money:";
            l_Rank.Text = "Rank:";
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            L_PD_PlayerData.Clear();
            L_S_PlayerDataLoc.Clear();
            treeView1.Nodes.Clear();
            Save.Enabled = false;
            Delete.Enabled = false;
            textBox1.Enabled = false;
            textBox2.Enabled = false;
            textBox3.Enabled = false;
        }
        private void Delete_Click(object sender, EventArgs e)
        {
            if (Ask)
            {
                DialogResult dialogResult = MessageBox.Show("Going to delete: " + treeView1.SelectedNode.Text + " Are you sure?", "Delete?", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    try
                    {
                        File.Delete(L_S_PlayerDataLoc[treeView1.SelectedNode.Index]);
                        ClrReset();
                        Load_DataBase(false);
                    }
                    catch
                    {
                        MessageBox.Show("Invalid File / No File Selected.");
                    }
                }
                else if (dialogResult == DialogResult.No)
                {
                    //you chose no! :O
                }
            }
            else
            {
                try
                {
                    File.Delete(L_S_PlayerDataLoc[treeView1.SelectedNode.Index]);
                    ClrReset();
                    Load_DataBase(false);
                }
                catch
                {
                    MessageBox.Show("Invalid File / No File Selected.");
                }
            }
        }

        private void Update_Click(object sender, EventArgs e)
        {
            ClrReset();
            MessageBox.Show("Reloading Players");
            Load_DataBase(true);
        }

        private void NewPlayer_Click(object sender, EventArgs e)
        {
            NewFileCnt++;
            PlayerData CoolGuy;
            CoolGuy.Name = "CoolGuy" + NewFileCnt;
            CoolGuy.Money = 420;
            CoolGuy.Rank = 69;

            String Temp = JsonConvert.SerializeObject(CoolGuy);
            File.WriteAllText("CoolGuy"+NewFileCnt+".txt", Temp);
            ClrReset();
            Load_DataBase(false);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            Ask = checkBox1.Checked;
        }

        private void Save_Click(object sender, EventArgs e)
        {
            DoSave();
        }
        void DoSave()
        {
            File.Delete(L_S_PlayerDataLoc[treeView1.SelectedNode.Index]);
            String JsonText = JsonConvert.SerializeObject(SelectedPlayerData);
            File.WriteAllText(Directory.GetCurrentDirectory() + "/" + SelectedPlayerData.Name+".txt", JsonText);
            ClrReset();
            Load_DataBase(false);
        }
        //name input
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(e.KeyChar == 13)
            {
                SelectedPlayerData.Name = textBox1.Text;
                treeView1.SelectedNode.Text = textBox1.Text+" [Unsaved Changes]";
                L_PD_PlayerData[treeView1.SelectedNode.Index] = SelectedPlayerData;
                textBox1.Text = "" + SelectedPlayerData.Name;
                treeView1.Focus();
                //DoSave();
                Save.Enabled = true;
            }
        }
        //money input
        private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                UInt64 NewNumber;
                if (UInt64.TryParse(textBox2.Text, out NewNumber))
                {
                    SelectedPlayerData.Money = NewNumber;
                    treeView1.SelectedNode.Text = SelectedPlayerData.Name + " [Unsaved Changes]";
                    L_PD_PlayerData[treeView1.SelectedNode.Index] = SelectedPlayerData;
                }
                textBox2.Text = "" + SelectedPlayerData.Money;
                treeView1.Focus();
                //DoSave();
                Save.Enabled = true;
            }
        }
        //rank input
        private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                int NewNumber;
                if (int.TryParse(textBox3.Text, out NewNumber))
                {
                    SelectedPlayerData.Rank = NewNumber;
                    treeView1.SelectedNode.Text = SelectedPlayerData.Name + " [Unsaved Changes]";
                    L_PD_PlayerData[treeView1.SelectedNode.Index] = SelectedPlayerData;
                }
                textBox3.Text = "" + SelectedPlayerData.Rank;
                treeView1.Focus();
                //DoSave();
                Save.Enabled = true;
            }
        }

        private void textBox1_Leave(object sender, EventArgs e)
        {
            textBox1.Text = "" + SelectedPlayerData.Name;
        }

        private void textBox2_Leave(object sender, EventArgs e)
        {
            textBox2.Text = "" + SelectedPlayerData.Money;
        }

        private void textBox3_Leave(object sender, EventArgs e)
        {
            textBox3.Text = "" + SelectedPlayerData.Rank;
        }
    }
}
